﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Dyd.BaseService.ConfigManager.Domain;
using Dyd.BaseService.ConfigManager.Domain.Dal;
using Dyd.BaseService.ConfigManager.Domain.Model;
using Dyd.BaseService.ConfigManager.Web.Tools;
using XXF.Db;
using XXF.ProjectTool;

namespace Dyd.BaseService.ConfigManager.Web.Controllers
{
    public class OpenApiController : Controller
    {
        //
        // GET: /OpenApi/
        /// <summary>
        /// 读取webconfig配置
        /// </summary>
        public static string Tokens = System.Configuration.ConfigurationManager.AppSettings["Token"];

        /// <summary>
        /// 获取配置
        /// </summary>
        /// configids ,分隔多个configids
        /// <param name="token"></param>
        /// <returns></returns>
        public ActionResult GetConfig(string token, string configids)
        {
            if (CheckToken(token))
            {
                using (DbConn conn = DbConfig.CreateConn(DataConfig.ConfigMangeConnectString))
                {
                    conn.Open();
                     List<int> os = new List<int>();
                    foreach(var o in configids.Trim(',').Split(','))
                    {
                        int v;
                        if(int.TryParse(o,out v))
                            os.Add(v);
                    }
                    var ms = new Domain.Dal.tb_config_dal().GetListByConfigids(conn, os);
                    var rs = ToConfigInfoModels(ms);
                    return Json(new XXF.Api.ServerResult() { code = 1, msg = "", response = rs, total = rs.Count });
                }
            }
            else
                return Json(new XXF.Api.ServerResult() { code = -1, msg = "出错", response = new { }, total = 0 });
        }
        /// <summary>
        /// 设置某个配置的负载均衡的负载权重
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public ActionResult SetLoadBalanceBoostPercent(string token, int configid, int sequence, int setboostpercent)
        {
            if (CheckToken(token))
            {
                using (DbConn conn = DbConfig.CreateConn(DataConfig.ConfigMangeConnectString))
                {
                    try
                    {
                        conn.Open();
                        conn.BeginTransaction();
                        var c = new Domain.Dal.tb_config_dal().Get(conn, configid);
                        var r = new Domain.Dal.tb_loadbalance_dal().SetBoostPercent(conn, configid, sequence, setboostpercent);
                        RedisHelper.SendCommand(new XXF.BaseService.ConfigManager.SystemRuntime.ConfigNetCommand()
                        {
                            CategoryID = c.categoryid,
                            CommandType = XXF.BaseService.ConfigManager.SystemRuntime.EnumCommandType.ConfigUpdate,
                            ProjectName = ""
                        });
                        conn.Commit();
                        return Json(new XXF.Api.ServerResult() { code = 1, msg = "成功", response = new { }, total = 0 });
                    }
                    catch (Exception exp)
                    {
                        conn.Rollback();
                    }
                    return Json(new XXF.Api.ServerResult() { code = -1, msg = "出错", response = new { }, total = 0 });
                }
            }
            else
                return Json(new XXF.Api.ServerResult() { code = -1, msg = "出错", response = new { }, total = 0 });
        }
        /// <summary>
        /// 设置某个配置的故障转移到某个转移项
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public ActionResult SetFailoverSequence(string token, int configid, int failoversequence)
        {
            if (CheckToken(token))
            {
                using (DbConn conn = DbConfig.CreateConn(DataConfig.ConfigMangeConnectString))
                {
                    try
                    {
                        conn.Open();
                        conn.BeginTransaction();
                        var c = new Domain.Dal.tb_config_dal().Get(conn, configid);
                        var r = new Domain.Dal.tb_config_dal().SetFailoverSequence(conn, configid, failoversequence);
                        RedisHelper.SendCommand(new XXF.BaseService.ConfigManager.SystemRuntime.ConfigNetCommand()
                        {
                            CategoryID = c.categoryid,
                            CommandType = XXF.BaseService.ConfigManager.SystemRuntime.EnumCommandType.ConfigUpdate,
                            ProjectName = ""
                        });
                        conn.Commit();
                        return Json(new XXF.Api.ServerResult() { code = 1, msg = "成功", response = new { }, total = 0 });
                    }
                    catch (Exception exp)
                    {
                        conn.Rollback();
                    }
                    return Json(new XXF.Api.ServerResult() { code = -1, msg = "出错", response = new { }, total = 0 });
                }
            }
            else
                return Json(new XXF.Api.ServerResult() { code = -1, msg = "出错", response = new { }, total = 0 });
        }

        private bool CheckToken(string token)
        {
            if (Tokens.Contains(";" + token + ";"))
            {
                return true;
            }
            return false;
        }

        private List<ConfigInfoModel> ToConfigInfoModels(List<tb_config_model> models)
        {

            List<int> loadbalanceconfigids = new List<int>();
            List<int> failoverconfigids = new List<int>();
            foreach (var m in models)
            {
                if (m.loadbalancealgorithmenum >= 0)
                {
                    loadbalanceconfigids.Add(m.id);
                }
                if (m.failoversequence >= 0)
                {
                    failoverconfigids.Add(m.id);
                }
            }
            List<tb_loadbalance_model> loadbalancemodels = new List<tb_loadbalance_model>();
            Dictionary<int, Dictionary<string, tb_loadbalance_model>> loadbalancemodelsdic = new Dictionary<int, Dictionary<string, tb_loadbalance_model>>();
            List<tb_failover_model> failovermodels = new List<tb_failover_model>();
            Dictionary<int, Dictionary<string, tb_failover_model>> failovermodelsdic = new Dictionary<int, Dictionary<string, tb_failover_model>>();
            SqlHelper.ExcuteSql(DataConfig.ConfigMangeConnectString, (c) =>
            {
                loadbalancemodels = new tb_loadbalance_dal().GetListByCategoryIDs(c, loadbalanceconfigids);
                failovermodels = new tb_failover_dal().GetListByCategoryIDs(c, failoverconfigids);
            });

            foreach (var m in loadbalancemodels)
            {
                if (!loadbalancemodelsdic.ContainsKey(m.configid))
                {
                    loadbalancemodelsdic.Add(m.configid, new Dictionary<string, tb_loadbalance_model>());
                }
                loadbalancemodelsdic[m.configid].Add(m.sequence.ToString(), m);
            }

            foreach (var m in failovermodels)
            {
                if (!failovermodelsdic.ContainsKey(m.configid))
                {
                    failovermodelsdic.Add(m.configid, new Dictionary<string, tb_failover_model>());
                }
                failovermodelsdic[m.configid].Add(m.sequence.ToString(), m);
            }

            List<ConfigInfoModel> rs = new List<ConfigInfoModel>();
            foreach (var m in models)
            {
                var r = new ConfigInfoModel();
                r.configmodel = m;
                if (loadbalancemodelsdic.ContainsKey(m.id))
                    r.loadbalacemodels = loadbalancemodelsdic[m.id];
                if (failovermodelsdic.ContainsKey(m.id))
                    r.failovermodels = failovermodelsdic[m.id];
                rs.Add(r);
            }
            return rs;
        }
    }

    [Serializable]
    public class ConfigInfoModel
    {
        public tb_config_model configmodel { get; set; }
        public Dictionary<string, tb_loadbalance_model> loadbalacemodels { get; set; }
        public Dictionary<string, tb_failover_model> failovermodels { get; set; }
    }
}
